﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Entities;
using Atmk.WaterMeter.MIS.Entities.Models;
using Atmk.WaterMeter.MIS.Services.DataAccess.Base;
using Microsoft.EntityFrameworkCore;

namespace Atmk.WaterMeter.MIS.Services.DataAccess
{
    /// <summary>
    /// 阶梯价格
    /// </summary>
    public class StepTariffRepository : BaseRepository, IStepTariffRepository
    {
        private readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        /// <inheritdoc />
        /// <summary>
        /// 查询价格名称
        /// </summary>
        /// <param name="priceId"></param>
        /// <returns></returns>
        public string GetPriceName(string priceId)
        {
            var prices = FindAllAsNoTracking<PrcieStep>().Where(p => p.Id.ToString() == priceId).ToList();
            if (prices.Count != 0) return prices.First().Name;
            _logger.Warn("未查到价格对象");
            return "";
        }

        /// <inheritdoc />
        public Dictionary<string, PrcieStep> GetMeterNumberPriceStep(params Meter[] meters)
        {
            var result = new Dictionary<string, PrcieStep>();
            var pricts = Context.PrcieStep.AsNoTracking();
            foreach (var entity in meters)
            {
                try
                {
                    result[entity.MeterNumber] = pricts.First(p => p.Id.ToString() == entity.PrcieStepId);
                }
                catch (InvalidOperationException e)
                {
                  _logger.Error(e,$"水表{entity.MeterNumber}未设置阶梯水价");
                }
                
            }
            return result;
        }

        /// <summary>
        /// 获取该项目id下的所有价格信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public List<PrcieStep> GetPrcieStepList(string projectId)
        {
            return Context.PrcieStep.Where(p => p.ProjectId == projectId).ToList();
        }

        /// <summary>
        /// 获取指定阶梯价格下的费用信息
        /// </summary>
        /// <param name="PrcieStepId"></param>
        /// <returns></returns>
        public List<FeePrice> GetPrcieStepFeeList(params PrcieStep[] PrcieStepId)
        {
            return Context.FeePrice.Where(f => PrcieStepId.Select(p => p.Id).Contains(f.PiceStepId)).ToList();
        }
    }
}